//
//  LoginViewController.m
//  CarUser
//
//  Created by ayi on 2018/12/26.
//  Copyright © 2018 王森林. All rights reserved.
//

typedef NS_OPTIONS(NSUInteger, CustomShareType) {
    Login_WeChat = 1 << 0,
    Login_XinLang = 1 << 1,
    Login_QQ = 1 << 2,
};


#import "LoginViewController.h"
#import "UserRes.h"
#import "ForgetPWViewController.h"
#import <YYCategories/UIView+YYAdd.h>
@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIView *phoneBgView;
@property (weak, nonatomic) IBOutlet UIView *passwordBgView;
@property (weak, nonatomic) IBOutlet UIButton *forgetPasswordBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIView *thirdLoginBtnBgView;//第三方登录按钮view
@property (weak, nonatomic) IBOutlet UIView *bottomView;//
@property (weak, nonatomic) IBOutlet UITextField *mobileField;
@property (weak, nonatomic) IBOutlet UITextField *pwField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//     self.fd_prefersNavigationBarHidden = YES;
    self.scrollview.backgroundColor = UIColor.clearColor;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"nav_back"]
                                                                                   imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                                                            style:UIBarButtonItemStylePlain
                                                                           target:self
                                                                           action:@selector(backAction)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(pushToRegister)];
    
    self.phoneBgView.layer.masksToBounds = YES;
    self.phoneBgView.layer.cornerRadius = 22;
    
    self.passwordBgView.layer.masksToBounds = YES;
    self.passwordBgView.layer.cornerRadius = 22;

    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 22;
    if (![CommonMethod isBlankString:[CommonMethod getUserName]]) {
        self.mobileField.text = [CommonMethod getUserName];
    }
    
    
    [self downLoginBtnCreate];
    
    @weakify(self);
    self.loginBtn.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        @strongify(self);
        
        RACSignal *sign = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//            [subscriber sendCompleted];
            
            if ([CommonMethod isBlankString:self.mobileField.text]) {
                
                [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
                [subscriber sendCompleted];
                return nil;
            }
            if ([CommonMethod isBlankString:self.pwField.text]) {
                
                [SVProgressHUD showErrorWithStatus:@"请输入密码"];
                [subscriber sendCompleted];
                return nil;
            }
            
            
            NSDictionary *params = @{
                                     @"FKEY":[CommonMethod createMD5Key:@"USERNAME"],
                                     @"USERNAME":self.mobileField.text,
                                     @"TYPE":@"1",
                                     @"PASSWORD":[CommonMethod createShaKey:[NSString stringWithFormat:@"%@%@",self.pwField.text,self.mobileField.text]]
                                     };
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showWithStatus:nil];
            });
            
            [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_Login params:params md5Paraname:@"" success:^(id  _Nullable response) {
               
                UserRes *userRes = [UserRes yy_modelWithDictionary:response];
                userRes.mobile = self.mobileField.text;
                [CommonMethod saveUser:userRes];
                [CommonMethod saveUserName:self.mobileField.text];
                [self dismissViewControllerAnimated:YES completion:nil];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_Fresh_Userinfo object:nil];
                [subscriber sendCompleted];
                
            } fail:^(NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                });
                [subscriber sendCompleted];
            }];
            
            
            
            return nil;
        }];
        return sign;
        
    }];
}

- (IBAction)handleForgetAction:(id)sender
{
    
    ForgetPWViewController *controller = [[ForgetPWViewController alloc] init];
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)backAction{
    [self.view endEditing:YES];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)pushToRegister{
    [self performSegueWithIdentifier:@"register" sender:nil];
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
   
}

- (void)btnAction:(UIButton *)btn{
    NSLog(@"登录中");
}






- (void)handleCallAction
{
    
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"400-1060988"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)downLoginBtnCreate{
    
    [_thirdLoginBtnBgView removeAllSubviews];
    
    UIButton *mobileBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    mobileBtn.frame = CGRectMake(0, 20, BOUNDWIDTH, 40);
    [mobileBtn setTitle:@"400-1060988" forState:UIControlStateNormal];
    [mobileBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [mobileBtn setImage:IMG(@"login1") forState:UIControlStateNormal];
    [mobileBtn addTarget:self action:@selector(handleCallAction) forControlEvents:UIControlEventTouchUpInside];
    [_thirdLoginBtnBgView addSubview:mobileBtn];
    
//    NSArray *ary = @[
//                     @(Login_XinLang),
//                     @(Login_WeChat),
//                     @(Login_QQ)
//                     ];
//
//    __block NSInteger count = 0;
//    CGFloat width = 40;
//    @weakify(self);
//    [ary enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        @strongify(self);
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.tag = 1000 + [obj integerValue];
//        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
//        switch ([obj integerValue]) {
//            case Login_XinLang:
//            {
//                [btn setImage:IMG(@"ic_login_weibo") forState:UIControlStateNormal];
//            }
//                break;
//            case Login_WeChat:
//            {
//                [btn setImage:IMG(@"ic_login_wechat") forState:UIControlStateNormal];
//            }
//                break;
//            case Login_QQ:
//            {
//                [btn setImage:IMG(@"ic_login_qq") forState:UIControlStateNormal];
//            }
//                break;
//            default:
//                [btn setTitle:@"" forState:UIControlStateNormal];
//                break;
//        }
//        CGFloat customWitdth = [UIScreen mainScreen].bounds.size.width;
//
//        if (ary.count <= 4) {
//            CGFloat clipwidth = 60;
//            customWitdth -= clipwidth;
//            btn.frame = CGRectMake(clipwidth/2 + customWitdth/ary.count * idx + (customWitdth/ary.count - width)/2, 20, width, width);
//        }else{
//            if (idx != 0 && idx % 5  == 0) {
//                count ++;
//            }
//            btn.frame = CGRectMake(customWitdth/5 * (idx % 5) + (customWitdth/5 - width)/2, 20 + count * width, width, width);
//        }
//        [self.thirdLoginBtnBgView addSubview:btn];
//    }];
    
    
    
}



@end
